package com.yonyou.crm.sact.visit.appctrl;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.*;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.base.AppBaseCtrl;
import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.rest.constant.AppCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sact.outwork.entity.TraceVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleStatusEnum;
import com.yonyou.crm.sact.visit.entity.VisitsVO;
import com.yonyou.crm.sact.visit.rmitf.IVisitsRmService;

@RestController
@RequestMapping(value = "/{version}/msact/visits")
public class AppVisitCtrl extends AppBaseCtrl {
	
	@Autowired
	private IVisitsRmService service;
	
	/**
	 * 查询拜访计划
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object getlist(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> searchMap = new HashMap<String, Object>();
		
		String dateStr = paramObj.getString("date");
		Date date = transformDateFromStr(dateStr, "yyyy-MM-dd");
		searchMap.put("date", date) ;
		
		List<String> filter = JSONArray.toList(JSONArray.fromObject(paramObj.get("filter")), new String(), new JsonConfig());
		if (filter != null) {
			searchMap.put("filter", filter) ;
		}
		
		List<VisitsVO>  visitList = service.getScheduleList(searchMap);
		
		Map<String, Object> res = new HashMap<String, Object>();
		long totalNum = visitList.size();
		res.put("totalnum", totalNum);
		List<Map<String, Object>> scheduleList = new ArrayList<Map<String, Object>>();
		long completeNum = 0;
		long uncompleteNum = 0;
		for(int i = 0 ; i < totalNum; i++) {
			VisitsVO visit = visitList.get(i);
			Map<String, Object> schedule = new HashMap<String, Object>();
			String status = String.valueOf(visit.getStatus());
			if (String.valueOf(ScheduleStatusEnum.NOT_START.getValue()).equals(status)) {
				schedule.put("status", ScheduleStatusEnum.NOT_START.getValue());
				uncompleteNum ++;
			} else if (String.valueOf(ScheduleStatusEnum.IN_HAND.getValue()).equals(status)) {
				schedule.put("status", ScheduleStatusEnum.IN_HAND.getValue());
				uncompleteNum ++;
			} else if (String.valueOf(ScheduleStatusEnum.COMPLETED.getValue()).equals(status)) {
				schedule.put("status", ScheduleStatusEnum.COMPLETED.getValue());
				completeNum ++;
			} else {
				//nothing
			}
			
			schedule.put("id", visit.getId());
			schedule.put("accountname", visit.getId());
			CustomerVO cum = visit.getCumInfo();
			String addr = "";
			if (cum != null) {
				addr = cum.getProvinceName()+cum.getCityName()+cum.getDistrictName()+cum.getStreet();
			}
			schedule.put("accountaddress", addr);
			schedule.put("status", visit.getStatus());
			schedule.put("type", visit.getType());
			schedule.put("owner", visit.getOwnerInfo().getName());
			schedule.put("ownerdept", "");
			scheduleList.add(schedule);
		}
		
		res.put("schedulelist", scheduleList);
		res.put("uncompletenum", uncompleteNum);
		res.put("completenum", completeNum);
		
		return ResponseUtil.getObject(res);
	}
	
	/**
	 * 客户拜访日历日期列表
	 * @param version
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="datelist", method = RequestMethod.GET)
	public Object getDateList(@PathVariable("version") String version, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		JSONObject paramObj = RequestUtil.getParamObject(request);
		Map<String, Object> searchMap = new HashMap<String, Object>();
		
		String startDateStr = paramObj.getString("startdate");
		Date startDate = transformDateFromStr(startDateStr, "yyyy-MM-dd");
		searchMap.put("startDate", startDate) ;
		
		String endDateStr = paramObj.getString("enddate");
		Date endDate = transformDateFromStr(endDateStr, "yyyy-MM-dd");
		searchMap.put("endDate", endDate) ;

		List<String>  dateList = service.getScheduleDateList(searchMap);
		
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("datelist", dateList);
		
		return ResponseUtil.getObject(res);
	}

	/**
	 * 拜访计划详情
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ServerError, "id不能为空");
		}		
		
		return ResponseUtil.getObject(service.getDetail(id));
	}
	
	
	/**
	 * 保存拜访计划
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="{id}", method = RequestMethod.POST)
	public Object save(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		// VisitsVO visit = RequestUtil.getVO(request, VisitsVO.class);
		VisitsVO visit = new VisitsVO();
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		
		String dateStr = paramObj.getString("date");
		Date date = transformDateFromStr(dateStr, "yyyy-MM-dd");
		visit.setDate(date);
		
		long cumId = Long.parseLong(paramObj.getString("accountid"));
		visit.setCumId(cumId);
		
		String contactId = paramObj.getString("contactid");
		visit.setContactId(contactId);
		
		long bizoppId = Long.parseLong(paramObj.getString("bizoppid"));
		visit.setOpportunityId(bizoppId);
		
		String purpose = paramObj.getString("purpose");
		visit.setPurpose(purpose);
		
		String validMsg = insertValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(validMsg);
		}
		
		if (id == 0) {
			visit = service.insert(visit);
		} else {
			visit.setId(id);
			visit = service.update(visit);
		}
		
		if (visit.getId() == null) {
			throw new CrmMessageException(AppCodeConstant.ServerError, "获取自增主键为空");
		}
				
		return ResponseUtil.getObject();
	}

	/**
	 * 拜访计划新增校验
	 * @param visit
	 * @return String
	 */
	private String insertValidator(VisitsVO visit) {
		
		if (visit == null) {
			return "转换实体失败";
		}
		
		if (visit.getDate() == null) {
        	return  "拜访日期不能为空";
		}
		
		if (visit.getCumId() == 0) {
        	return  "客户不能为空";
		}
		
		if (!StringUtils.isNotBlank(visit.getPurpose())) {
        	return  "拜访目的不能为空";
		}
		
		return "";
	}
	
	/**
	 * 拜访小结校验
	 * @param visit
	 * @return String
	 */
	private String updateValidator(VisitsVO visit) {
		
		if (visit == null) {
			return "转换实体失败";
		}
		
		if (!StringUtils.isNotBlank(visit.getSummary())) {
        	return  "拜访总结不能为空";
		}
		
		return "";
	}

	/**
	 * 拜访小结
	 * @param version
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value="{id}/summary", method = RequestMethod.PUT)
	public Object summary(@PathVariable("version") String version, @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		
		// VisitsVO visit = RequestUtil.getVO(request, VisitsVO.class);
		VisitsVO visit = new VisitsVO();
		
		JSONObject paramObj = RequestUtil.getParamObject(request);

		String nextDateStr = paramObj.getString("nextdate");
		Date nextDate = transformDateFromStr(nextDateStr, "yyyy-MM-dd");
		visit.setNextDate(nextDate);
		
		String summary = paramObj.getString("summary");
		visit.setSummary(summary);
		
		String validMsg = updateValidator(visit);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(validMsg);
		}

		visit.setId(id);
		visit = service.update(visit);
				
		return ResponseUtil.getObject(visit);
	}
	
		
	/**
	 * 删除拜访计划
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	public Object delete(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		
		service.delete(id);
		
		return ResponseUtil.getObject();
	}
	
	/**
	 * 日程签到
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}/locations", method = RequestMethod.POST)
	public Object location(@PathVariable("id") Long id ,HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(AppCodeConstant.ClientError, "id不能为空");
		}
		TraceVO trace = new TraceVO();
		
		service.location(id, trace);
		
		return ResponseUtil.getObject();
	}
	
}
